import { createRouter, createWebHistory } from 'vue-router'
import { Progress } from '@/utils/progress'

// layouts
import BasicLayout from '@/layouts/basic-layout/index.vue'
import UserLayout from '@/layouts/user-layout/index.vue'

// pages
import Bootstrap from '@/views/Bootstrap.vue'
import NotFound from '@/views/NotFound.vue'

// routes
import routes from '~pages'

import { useAppStore } from '@/stores/app'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/bootstrap',
      name: 'bootstrap',
      component: Bootstrap
    },
    // 测试页面
    {
      path: '/play',
      name: 'play',
      component: () => import('../views/Play.vue')
    },
    {
      path: '/user',
      component: UserLayout,
      children: [
        {
          path: '/login',
          name: 'login',
          component: () => import('../views/Login.vue')
        }
      ]
    },
    {
      path: '',
      component: BasicLayout,
      meta: { requiresAuth: true },
      children: [
        ...routes,
        {
          path: '/:pathMatch(.*)*',
          name: 'NotFound',
          component: NotFound
        }
      ]
    }
  ]
})

router.beforeEach(async (to) => {
  Progress.start()

  if (to.meta.requiresAuth) {
    const store = useAppStore()
    // 判断是否已登录
    if (!store.token) {
      return { name: 'login' }
    }
    // 判断是否已初始化数据
    if (!store.isReady) {
      return { name: 'bootstrap' }
    }
  }

  return true
})

router.afterEach(() => {
  Progress.done()
})

export default router
